<template>
  <div>
    <form-marker-biserial
      :isEdit="isEditPage"
      :formData="list" 
      :rulesList="rules"
      :selectList="selectData"
      :eidtList="detailData"
      v-on:on-validateDate="onValidate"
      v-on:on-confirm="onSaveInfo" 
      v-on:on-cancel="onCancelInfo"></form-marker-biserial>
  </div>
</template>
<script>
import FormMarkerBiserial from '@/components/createPage/createBiserial'
import {isPositiveInteger} from '@/common/utils'
export default {
  components: {
    FormMarkerBiserial
  },
  data () {
    // 自定义验证规则
    let checkInteger = (rule, value, callback) => {
      let reg = /^(0|\+?[1-9][0-9]*)$/g
      if (value && !reg.test(value)) {
        callback(new Error('请输入正整数'))
      } else {
        callback()
      }
    }
    let checkFloat = (rule, value, callback) => {
      let reg = /^(?!0+(?:\.0+)?$)(?:[1-9]\d*|0)(?:\.\d{1,2})?$/
      if (value && !reg.test(value)) {
        callback(new Error('请输入数字且小数点后最多四位，请重新输入'))
      } else {
        callback()
      }
    }
    let checkNumber = (rule, value, callback) => {
      if (value && !isPositiveInteger(value)) {
        callback(new Error('请输入数字'))
      } else {
        callback()
      }
    }
    // 自定义验证规则
    let checkDate = (rule, value, callback) => {
      // let currentDate = new Date(value).getTime()
      let currentMarketDate = this.dataValue.marketDate && new Date(this.dataValue.marketDate).getTime()
      let currentDelistingDate = this.dataValue.delistingDate && new Date(this.dataValue.delistingDate).getTime()
      let currentOrderDeadline = this.dataValue.orderDeadline && new Date(this.dataValue.orderDeadline).getTime()
      if (this.dataValue.type === 'delistingDate' && currentMarketDate && (currentDelistingDate < currentMarketDate || currentDelistingDate === currentMarketDate)) {
        callback(new Error('退市日期必须大于上市日期'))
      } else if (this.dataValue.type === 'marketDate' && currentDelistingDate && (currentDelistingDate < currentMarketDate || currentDelistingDate === currentMarketDate)) {
        callback(new Error('上市日期必须小于退市日期'))
      } else if (this.dataValue.type === 'orderDeadline' && currentMarketDate && currentDelistingDate && (currentOrderDeadline < currentMarketDate || currentOrderDeadline === currentMarketDate || currentOrderDeadline > currentDelistingDate)) {
        callback(new Error('订货截止日期必须在上市日期必须与退市日期之间'))
      } else {
        callback()
      }
    }
    return {
      formInline: {},
      classList: [],
      props: {
        value: 'label',
        children: 'cities'
      },
      isEditPage: false,
      selectData: {},
      detailData: {},
      list: [
        {
          title: '基本信息',
          leftChild: [
            {
              type: 'cascader',
              label: '商品分类',
              name: '商品分类',
              prop: 'productType',
              classList: 'classList'
            },
            {
              type: 'input',
              label: '商品英文全称',
              prop: 'enName'
            },
            {
              type: 'select',
              label: '系列',
              prop: 'seriesCode',
              propName: 'seriesName',
              optionLabel: 'name',
              optionValue: 'code'
            },
            {
              type: 'input',
              label: '商品条形码',
              prop: 'barcode'
            },
            {
              type: 'input',
              label: '供货商货号',
              prop: 'providerCode'
            },
            {
              type: 'input',
              label: '产地',
              prop: 'placeOfOrigin'
            }
          ],
          rightChild: [
            {
              type: 'input',
              label: '商品名称',
              prop: 'name'
            },
            {
              type: 'select',
              label: '品牌名称',
              prop: 'brandCode',
              propName: 'brandName',
              optionLabel: 'name',
              optionValue: 'code'
            },
            {
              type: 'select',
              label: '味道',
              prop: 'tasteCode',
              propName: 'tasteName',
              optionLabel: 'name',
              optionValue: 'code'
            },
            {
              type: 'input',
              label: '商品条形码(辅助)',
              prop: 'auxiliaryBarcode'
            },
            {
              type: 'input',
              label: '税率',
              prop: 'taxRate'
            },
            {
              type: 'input',
              label: '标准零售价(元)',
              prop: 'retailPrice'
            }
          ]
        },
        {
          title: '规格信息',
          leftChild: [
            {
              type: 'select',
              label: '单位',
              prop: 'unitCode',
              propName: 'unitName',
              optionLabel: 'unitName',
              optionValue: 'code'
            },
            {
              type: 'input',
              label: '保质期(月)',
              prop: 'warranty',
              inputType: 'number'
            },
            {
              type: 'input',
              label: '长(cm)',
              prop: 'length'
            },
            {
              type: 'input',
              label: '高(cm)',
              prop: 'height'
              // inputType: 'number'
            },
            {
              type: 'input',
              label: '重量(g)',
              prop: 'weight'
              // inputType: 'number'
            },
            {
              type: 'input',
              label: '小箱规',
              prop: 'secondSpecCode'
              // inputType: 'number'
            }
          ],
          rightChild: [
            {
              type: 'input',
              label: '规格(ml)',
              prop: 'specs'
            },
            {
              type: 'input',
              label: '最小起订量',
              prop: 'minOrderNumber'
            },
            {
              type: 'input',
              label: '宽(cm)',
              prop: 'width'
              // inputType: 'number'
            },
            {
              type: 'input',
              label: '体积(cm³)',
              prop: 'volume'
              // inputType: 'number'
            },
            {
              type: 'input',
              label: '大箱规',
              prop: 'firstSpecCode'
              // inputType: 'number'
            }
          ]
        },
        {
          title: '其他信息',
          leftChild: [
            {
              type: 'date',
              label: '上市日期',
              prop: 'marketDate'
            },
            {
              type: 'date',
              label: '订货截止时间',
              prop: 'orderDeadline'
            },
            {
              type: 'upload',
              label: '商品图片',
              prop: 'mainPicture'
            }
          ],
          rightChild: [
            {
              type: 'date',
              label: '退市日期',
              prop: 'delistingDate'
            },
            {
              type: 'checkout',
              label: '是否管理库存',
              prop: 'temp'
            }
          ]
        }
      ],
      dialogImageUrl: '',
      dialogVisible: false,
      rules: {
        productType: [
          { required: true, message: '商品分类不允许为空', trigger: 'change' }
        ],
        name: [
          { max: 64, message: '长度不可超过64个字符', trigger: 'blur' },
          { required: true, message: '商品名称不允许为空', trigger: 'blur' }
        ],
        enName: [
          { max: 64, message: '长度不可超过64个字符', trigger: 'blur' }
        ],
        brandCode: [{ required: true, message: '品牌名称不允许为空', trigger: 'change' }],
        seriesCode: [{ required: true, message: '系列不允许为空', trigger: 'change' }],
        tasteCode: [
          { required: true, message: '味道不允许为空', trigger: 'change' }
        ],
        barCode: [
          { max: 32, message: '长度不可超过32个字符', trigger: 'blur' },
          { required: true, message: '商品条形码不允许为空', trigger: 'blur' }
        ],
        goodsBarCodeHelp: [
          { max: 64, message: '长度不可超过64个字符', trigger: 'blur' },
          { required: true, message: '商品条形码（辅助）不允许为空', trigger: 'blur' }
        ],
        taxRate: [
          { max: 16, message: '长度不可超过16个字符', trigger: 'blur' },
          { required: true, message: '税率不允许为空', trigger: 'blur' }
        ],
        specs: [
          { max: 64, message: '长度不可超过64个字符', trigger: 'blur' },
          { required: true, message: '标准零售价不允许为空', trigger: 'blur' }
        ],
        unitCode: [{ required: true, message: '单位不允许为空', trigger: 'change' }],
        specification: [
          { max: 64, message: '长度不可超过64个字符', trigger: 'blur' },
          { required: true, message: '规格不允许为空', trigger: 'blur' }
        ],
        expirationDate: [
          { max: 64, message: '长度不可超过64个字符', trigger: 'blur' },
          { required: true, message: '保质期不允许为空', trigger: 'change' },
          { validator: checkNumber, trigger: 'change' }
        ],
        minOrderNumber: [
          { max: 64, message: '长度不可超过64个字符', trigger: 'blur' },
          { required: true, message: '最小起订量不允许为空', trigger: 'blur' },
          { validator: checkNumber, trigger: 'blur' }
        ],
        firstSpecCode: [
          { max: 64, message: '长度不可超过64位', trigger: 'blur' },
          { validator: checkInteger, trigger: 'change' }
        ],
        secondSpecCode: [
          { max: 64, message: '长度不可超过64位', trigger: 'blur' },
          { validator: checkInteger, trigger: 'change' }
        ],
        placeOfOrigin: [{ max: 64, message: '长度不可超过64个字符', trigger: 'blur' }],
        // firstSpecCode: [{max: 64, message: '长度不可超过64个字符', trigger: 'blur' }],
        length: [
          { max: 16, message: '长度不可超过16个位', trigger: 'blur' },
          { validator: checkFloat, trigger: 'change' }
        ],
        height: [
          { max: 16, message: '长度不可超过16个位', trigger: 'blur' },
          { validator: checkFloat, trigger: 'change' }
        ],
        weight: [
          { max: 16, message: '长度不可超过16个位', trigger: 'blur' },
          { validator: checkFloat, trigger: 'change' }
        ],
        width: [
          { max: 16, message: '长度不可超过16个位', trigger: 'blur' },
          { validator: checkFloat, trigger: 'change' }
        ],
        volume: [
          { max: 20, message: '长度不可超过16个位', trigger: 'blur' },
          { validator: checkFloat, trigger: 'change' }
        ],
        delistingDate: [
          { validator: checkDate, trigger: 'change' }
        ],
        marketDate: [
          { validator: checkDate, trigger: 'change' }
        ],
        orderDeadline: [
          { validator: checkDate, trigger: 'change' }
        ]
      },
      pageType: '',
      dataValue: null
    }
  },
  computed: {},
  created () {
    this.pageType = this.$route.params && this.$route.params.id
  },
  watch: {},
  mounted () {
    this.getProductClassSelect()
    this.getBrandSelect()
    this.getSeriaSelect()
    this.getSmellSelect()
    this.getUnitSelect()
    this.getGoodsDetail()
  },
  methods: {
    init () {},
    // 获取编辑详情数据
    async getGoodsDetail () {
      if (this.pageType !== 'new') {
        let {data} = await this.$http.post(`/${this.$const.PREFIX.MAINDATA}/mproducts/getOne`, {id: this.pageType})
        this.detailData = data
        this.isEditPage = true
      }
    },
    // 获取品牌下拉列表数据
    async getBrandSelect () {
      let {data} = await this.$http.post(`/${this.$const.PREFIX.MAINDATA}/mproductbrandtaste/list`, {itemType: 0})
      this.selectData.brandCode = data
      this.selectData = JSON.parse(JSON.stringify(this.selectData))
    },
    // 获取系列下拉列表数据
    async getSeriaSelect () {
      let {data} = await this.$http.post(`/${this.$const.PREFIX.MAINDATA}/mproductclasses/list`, {itemType: 1})
      this.selectData.seriesCode = data
      this.selectData = JSON.parse(JSON.stringify(this.selectData))
    },
    // 获取味道下拉列表数据
    async getSmellSelect () {
      let {data} = await this.$http.post(`/${this.$const.PREFIX.MAINDATA}/mproductbrandtaste/list`, {itemType: 1})
      this.selectData.tasteCode = data
      this.selectData = JSON.parse(JSON.stringify(this.selectData))
    },
    // 获取单位下拉列表数据
    async getUnitSelect () {
      let {data} = await this.$http.post(`/${this.$const.PREFIX.MAINDATA}/mproductunits/list`, {})
      this.selectData.unitCode = data
      this.selectData = JSON.parse(JSON.stringify(this.selectData))
    },
    // 获取商品分类下拉列表数据
    async getProductClassSelect () {
      let {data} = await this.$http.post(`/${this.$const.PREFIX.MAINDATA}/mproductclasses/listParentClasses`, {itemType: 0})
      let currntList = data
      this.selectData.classList = currntList.map((val, index) => {
        this.getProductSelect(val, index)
        return {
          label: val.name,
          value: val.code,
          children: []
        }
      })
      this.selectData = JSON.parse(JSON.stringify(this.selectData))
    },
    async getProductSelect (valueData, index) {
      let {data} = await this.$http.post(`/${this.$const.PREFIX.MAINDATA}/mproductclasses/list`, {itemType: 0, parentCode: valueData.code})
      this.selectData.classList[index].children = data.map((val) => {
        return {
          label: val.name,
          value: val.code
        }
      })
    },
    onCancelInfo () {
      this.$router.push({name: 'goodsInfo'})
    },
    onSaveInfo (val) {
      // 调保存接口
      let url = this.pageType === 'new' ? `/${this.$const.PREFIX.MAINDATA}/mproducts/add` : `/${this.$const.PREFIX.MAINDATA}/mproducts/update`
      let obj = val
      // obj.itemType = '0'
      this.$http.post(url, obj).then((res) => {
        if (res.result) {
          this.$message.success('操作成功')
          this.$router.push({name: 'goodsInfo'})
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    handleRemove (file, fileList) {
      console.log(file, fileList)
    },
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    onValidate (val) {
      this.dataValue = val
    }
  }
}
</script>
<style lang="scss" scoped>
.goods-wrapper{
  background-color: white;
  padding: 20px;
  &_line{
    border-left: 5px #409EFF solid;
    margin: 20px 0;
  }
  .text_align{
    text-align: center
  }
}
</style>

